/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOMap;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 *
 * @author Tri
 */
public class DTMap {
    public static final String TABLE_NAME = "Map";
    private static DTMap instance = null;
    public static DTMap sharedInstance() {
        if(instance == null) {
            instance = new DTMap();
        }
        return instance;
    }
    private MongoOperations m_mongoOperations;
    private DTMap() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public void  insert(DOMap map) {
        m_mongoOperations.save(map, TABLE_NAME);
    }
    
    public boolean update(DOMap map) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMap.KEY_MAP_ID).is(map.getMapID()));
        
        DOMap resultQuery = m_mongoOperations.findOne(query, DOMap.class);
        if(resultQuery != null) {
            Update updateQuery = new Update();
            updateQuery.set(DOMap.KEY_COMPLETE_STEP, map.getCompleteSteps());
            updateQuery.set(DOMap.KEY_COMPLETE_TIME, map.getCompleteTime());
            updateQuery.set(DOMap.KEY_LEVEL, map.getLevel());
            updateQuery.set(DOMap.KEY_WON_MONEY, map.getWonMoney());
            updateQuery.set(DOMap.KEY_MATRIX, map.getMatrix());
            updateQuery.set(DOMap.KEY_SUB_OBSTACLE, map.getObstaclesList());
            updateQuery.set(DOMap.KEY_SPEED, map.getSpeed());
            
            m_mongoOperations.updateFirst(query, updateQuery, DOMap.class);
            return true;
        }
        
        return false;
    }
    
    public boolean  delete(String mapID) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMap.KEY_MAP_ID).is(mapID));
        DOMap result = m_mongoOperations.findOne(query, DOMap.class);
        if(result != null) {
            m_mongoOperations.remove(result);
            return true;
        }
        return false;
    }
    
    public DOMap getMap(String mapID) {
        DOMap map = null;
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMap.KEY_MAP_ID).is(mapID));
        map = m_mongoOperations.findOne(query, DOMap.class);
        return map;
    }
}
